package com.fyfeng.testsign;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends ActionBarActivity {

	private Context mContext;

	private ProgressDialog mProgressDialog;

	private final List<PackageInfo> mAppList = new ArrayList<PackageInfo>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mContext = this.getApplicationContext();

		initCreate();

	}

	private void initCreate() {

		android.os.AsyncTask<Void, Void, List<PackageInfo>> task = new android.os.AsyncTask<Void, Void, List<PackageInfo>>() {

			@Override
			protected void onPreExecute() {

				if (null == mProgressDialog) {
					mProgressDialog = ProgressDialog.show(MainActivity.this, null, "正在加载 ...", true, true);
					
				} else {
					mProgressDialog.show();
				}
			}

			@Override
			protected void onPostExecute(List<PackageInfo> result) {
				mProgressDialog.dismiss();
				loadAppListCallback(result);

			}

			@Override
			protected List<PackageInfo> doInBackground(Void... params) {

				PackageManager pm = mContext.getPackageManager();

				List<PackageInfo> list = pm.getInstalledPackages(0);
				
				return list;
			}
		};

		task.execute();

	}

	private void loadAppListCallback(List<PackageInfo> list) {

		mAppList.clear();

		mAppList.addAll(list);

		ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
		PackageManager pm = getPackageManager();
		for (PackageInfo info : list) {
			HashMap<String, String> map = new HashMap<String, String>();
			String appName = info.applicationInfo.loadLabel(pm).toString();
			map.put("appName", appName);
			data.add(map);
		}

		ListView listview = (ListView) this.findViewById(R.id.listview);

		String[] keys = new String[] { "appName" };
		int[] values = new int[] { R.id.list_item_appname };
		SimpleAdapter adapter = new SimpleAdapter(mContext, data, R.layout.listitem, keys, values);

		listview.setAdapter(adapter);

		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				onClickAppItem(mAppList.get(position));
			}
		});
	}

	private void onClickAppItem(PackageInfo packageInfo) {

		Intent intent = new Intent(this, AppDetailActivity.class);
		intent.putExtra(AppDetailActivity.ARGS_PACKAGEINFO, packageInfo);
		startActivity(intent);
	}

}
